package com.client;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.Inet4Address;
import java.nio.file.Paths;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.Scanner;

import com.http.HTTPResult;
import com.interf.Constant;
import com.interf.IRemoteRequester;
import com.interf.SyncTimeData;
import com.thread.RequestHandler;
import com.webhost.ClassFileServer;

public class ClientMain {
	
	private static final String FILE_NAME_TEST_PLAN = "D:\\testplan.txt";
	

	public static void main(String[] args) {
		
		int numThread = Integer.parseInt(TextFileUtil.readSomeLine(FILE_NAME_TEST_PLAN, 2, 2).get(0));
		
		String[] hostNames = TextFileUtil.convertToArray(TextFileUtil.readSomeLine(FILE_NAME_TEST_PLAN, 3, -1));
		//String[] hostNames = { "localhost", 
				//"192.168.2.103", 
				//"192.168.2.178"
		//		};
		
		
		
		long[] offsetTimes = new long[hostNames.length];
		if(System.getSecurityManager() == null) {
			System.setSecurityManager(new SecurityManager());
		}
		try {
			String classpath = ClientMain.class.getProtectionDomain().getCodeSource()
					.getLocation().getPath().toString();
			new ClassFileServer(2010, classpath);
			
			Scanner in = new Scanner(System.in);
			
			// Synctime code
			System.out.println(System.currentTimeMillis());
			for (int i = 0; i < hostNames.length; i++) {
				System.out.println("Trying to sync time with host: " + hostNames[i]);
				Registry registry = LocateRegistry.getRegistry(hostNames[i], Constant.RMI_PORT);
				IRemoteRequester rexecuter = (IRemoteRequester) registry.lookup(Constant.RMI_ID);
				long minOffset = Long.MAX_VALUE;
				for (int j = 0; j < 3; j++) {
					long requestTOL = System.currentTimeMillis();
					SyncTimeData syncTData = rexecuter.getSyncData();
					long responseTOA = System.currentTimeMillis();
					long delayTime = (responseTOA - requestTOL - (syncTData.responseToL - syncTData.requestToA))/2;
					long offset = responseTOA - syncTData.responseToL - delayTime;
					if (minOffset > offset) minOffset = offset;
				}
				System.out.println("Min offsetTime for host " + hostNames[i] + " is " + minOffset + " ms.");
				offsetTimes[i] = minOffset;
			}
			
			while (true) {
				System.out.print("Dest Host: ");
				String address = in.nextLine();
				String hostname = Inet4Address.getLocalHost().getHostName();
				RequestHandler handler = new RequestHandler(Inet4Address.getLocalHost().getHostName());
				handler.SendHTTPRequests(numThread, hostNames, address, offsetTimes, System.currentTimeMillis() + 5000);
				
				String[] logContent = new String[handler.results.size()*4];
				for (int i = 0; i < handler.results.size(); i++) {
					HTTPResult result = handler.results.get(i);
					//System.out.println("Avg time of the first slave test is: " + result.averageTime);
					logContent[i*4] = "Hostname: " + hostNames[i];
					logContent[i*4+1] = "Min time: " + result.minTime + " ms";
					logContent[i*4+2] = "Max time: " + result.maxTime + " ms";
					logContent[i*4+3] = "Average time: " + result.averageTime + " ms";
					
					
				}
				TextFileUtil.writeLog(logContent);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
